import dayjs, { Dayjs } from 'dayjs';
import { getCurrentViewNodes, toSecond } from '.';
import { Router } from '../autox/router';
import * as $ from './$';

/**
 * 输入关键字搜索，并随机进入一个 视频间
 * @param keyword 
 */
export function inputKeywordAndToVideoRoom(keyword: string) {
    const editor = $.getElementById('editor')
    const button = $.getElementById('right_button')
    $.setText(editor, keyword)
    sleep(1000)
    $.clickButton(button)
    /**
     * 等待网络加载 时间会有点长
     */
    $.waitForElementById('container')
    /**
     * 上划一下
     */
    $.swipeUp()
    sleep(1000)
    $.swipeUp()
    sleep(1000)
    $.clickButton($.getVisibleElementById('container'))
}


/**
 * 检查是否在首页
 * @returns 
 */
export function checkIsHome(times: number = 3) {
    const homeTab = selector().idContains('text1').textContains(`首页`).findOne(5000)
    if (!homeTab) {
        if (times <= -0) {
            return false;
        }
        return checkIsHome(times - 1)
    }
    if (homeTab.selected()) return true;
    $.clickButton(homeTab);
    return true;
}

export function waitOpenPackage(pkg: string) {
    const currentPackage = $.getCurrentPackage()
    if (currentPackage !== pkg) {
        $.launchPackage(pkg)
        sleep(1000)
    }
    selector().idContains('text1').textContains(`首页`).waitFor()
}


/**
 * 打开应用并进入快手视频间
 */
export function openAndJoinVideoRoom(pkg: string = $.PACKAGES['com.smile.gifmaker']) {
    waitOpenPackage(pkg)
    checkIsHome()
    sleep(1000)
    $.clickButton($.getElementById('search_btn'))
    sleep(1000)
    inputKeywordAndToVideoRoom(`美女`)
}

export function getRealLink(link: string) {
    const response = http.get(link)
    const url = response?.url.toString() as string;
    const [path, query] = url.split(`?`)
    const res = path.match(/fw\/live\/(.*)/)
    if (res && res.length > 0) {
        const [, ksid] = res;
        const params: any = {}
        query.split('&').map(key => {
            const [name, value] = key.split('=');
            params[name] = value;
        });
        return { ...params, ksid };
    }
}
/**
 * 进入直播间
 * @param pkg 
 */
export function openAndJoinLiveRoom(pkg: string = $.PACKAGES['com.smile.gifmaker']) {
    waitOpenPackage(pkg);
    sleep(2000)
    toastLog(`打开应用`)
    checkIsHome();
    toastLog(`检查是否首页`)
    sleep(1000);
    const tabNode = selector().visibleToUser(true).filter(it => {
        const text = it.desc()
        if (!text) return false;
        if (['小说', '直播', '放映厅', '生活', '热门', '探索'].includes(text)) {
            return true;
        }
        return false;
    });
    tabNode.waitFor();
    const ele = tabNode.findOne(3000);
    $.clickButton(ele);
    const liveNode = selector().visibleToUser(true).filter(it => {
        const text = it.text()
        if (!text) return false;
        if (text === '直播') {
            return true;
        }
        return false;
    }).findOne(3000);
    $.clickButton(liveNode);
    $.waitForElementById('live_explore_feed_card_layout')
    $.clickButton($.getElementById('live_explore_feed_card_layout'))
}


export function autoLookVideo() {
    /**
     * 先看4s
     */
    sleep(random(4000, 10000))
    if (Math.random() > 0.6) {
        $.clickButton($.getElementById('like_button'))
        sleep(1000)
    }
    if (Math.random() > 0.7) {
        $.clickButton($.getElementById('collect_button'))
        sleep(1000)
    }
    /**
     * 再看5s
     */
    sleep(random(4000, 10000))
}



declare const getClip: any;
export function getLiveRoomRedPacketInfo() {
    /**
    * 检查遮罩
    */
    // 等待10s
    // id("live_red_packet_status_text")
    const node = selector().visibleToUser(true).id('live_red_packet_status_text').findOne(random(10 * 1000, 12 * 1000))
    if (!node) throw new Error(`暂无红包`)
    // 可以进行点赞、关注、评论、红心操作
    const roomInfo = getLiveRoomInfo()
    if (!roomInfo) {
        // 等待5s退出
        throw new Error(`暂无红包`)
    }
    if (!roomInfo.live_name_text?.text) return toNextLiveRoom()
    toastLog(`欢迎来到【${roomInfo.live_name_text?.text}】的直播间，在线人数${roomInfo.live_audience_count_text?.text}人`)
    if (!roomInfo.live_red_packet_status_text?.text) {
        throw new Error(`暂无红包`)
    }
    const second = toSecond(roomInfo.live_red_packet_status_text.text)
    if (second <= 0) {
        throw new Error(`暂无红包`)
    }
    const getTime = roomInfo.open_time;
    const open_time = roomInfo.open_time.add(second, 'second') as Dayjs;
    $.clickButton(roomInfo.live_red_packet_status_text.node)
    sleep(3000)
    const redPackets = getRedPacketInfo()
    if (!redPackets) {
        throw new Error(`暂无红包`)
    }
    if (redPackets.length <= 0) {
        throw new Error(`暂无红包`)
    }
    /**
     * 有红包 区分红包类型及金额
     */
    let maxCount: number = 0;
    const redPacketsList = redPackets.map(it => {
        const text = it.__text as string;
        const isDefaultRedPacket = text.match(/主播的快币红包(.*?)快币(.*?)开奖时需要留在直播间/);
        if (isDefaultRedPacket && isDefaultRedPacket.length > 0) {
            const [, count, btn] = isDefaultRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, type: 0, btn: btn.trim(), text };
        }
        const isFansRedPacket = text.match(/主播的粉丝团红包(.*?)x(.*?)快币(.*?)加入主播粉丝团，即可参与抢红包/);
        if (isFansRedPacket && isFansRedPacket.length > 0) {
            const [, count, total, btn] = isFansRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, type: 1, total: parseInt(total.trim()), btn: btn.trim(), text };
        }
        const isCommentRedPacket = text.match(/主播的口令红包(.*?)快币 口令：(.*?)\s(.*?)\s在评论区发送口令，即可参与抢红包/)
        if (isCommentRedPacket && isCommentRedPacket.length > 0) {
            const [, count, comment, btn] = isCommentRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, comment, type: 2, btn: btn.trim(), text };
        }
        const isTimeRedPacket = text.match(/锦衣卫（5...的快币红包(.*?)快币(.*?)关注TA，更容易抢到红包/)
        if (isTimeRedPacket && isTimeRedPacket.length > 0) {
            const [, count, time] = isTimeRedPacket;
            const openTime = (getTime as Dayjs).add(parseInt(time.trim()), 'second')
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, time, type: 3, openTime, text };
        }
        const isShareRedPacket = text.match(/主播的分享红包(.*?)x(.*?)快币(.*?)分享直播间即可参与抢红包/)
        if (isShareRedPacket && isShareRedPacket.length > 0) {
            const [, count, total, btn] = isShareRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, total: parseInt(total.trim()), type: 4, btn: btn.trim(), text };
        }
        return { text };
    });;
    /**
     * 关闭
     */
    back()
    if (maxCount <= 0) throw new Error(`暂无红包`)
    sleep(2000)
    const roomLink = getRoomLink()
    const onLine = parseInt(roomInfo.live_audience_count_text?.text || '')
    return { redPacketsList, maxCount, onLine, ...roomLink, openTime: open_time.format('YYYY-MM-DD HH:mm:ss') };
}

export function getLiveRoomText() {
    const elements = selector().visibleToUser(true).textMatches(/.{1,9}/).find()
    const texts: string[] = []
    elements.each(ele => {
        const text = ele.text()
        texts.push(text)
    })
    return texts;
}

export function getRedPacketInfoSimple() {
    const redPackets = getRedPacketInfo()
    if (!redPackets) {
        throw new Error(`暂无红包`)
    }
    if (redPackets.length <= 0) {
        throw new Error(`暂无红包`)
    }
    /**
     * 有红包 区分红包类型及金额
     */
    let maxCount: number = 0;
    const redPacketsList = redPackets.map((it, index) => {
        const text = it.__text as string;
        const isDefaultRedPacket = text.match(/主播的快币红包(.*?)快币(.*?)开奖时需要留在直播间/);
        if (isDefaultRedPacket && isDefaultRedPacket.length > 0) {
            const [, count, btn] = isDefaultRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, type: 0, btn: btn.trim(), index, text };
        }
        const isFansRedPacket = text.match(/主播的粉丝团红包(.*?)x(.*?)快币(.*?)加入主播粉丝团，即可参与抢红包/);
        if (isFansRedPacket && isFansRedPacket.length > 0) {
            const [, count, total, btn] = isFansRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, type: 1, total: parseInt(total.trim()), btn: btn.trim(), index, text };
        }
        const isCommentRedPacket = text.match(/主播的口令红包(.*?)快币 口令：(.*?)\s(.*?)\s在评论区发送口令，即可参与抢红包/)
        if (isCommentRedPacket && isCommentRedPacket.length > 0) {
            const [, count, comment, btn] = isCommentRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, comment, type: 2, btn: btn.trim(), text, index };
        }
        const isTimeRedPacket = text.match(/锦衣卫（5...的快币红包(.*?)快币(.*?)关注TA，更容易抢到红包/)
        if (isTimeRedPacket && isTimeRedPacket.length > 0) {
            const [, count, time] = isTimeRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, time, type: 3, text, index };
        }
        const isShareRedPacket = text.match(/主播的分享红包(.*?)x(.*?)快币(.*?)分享直播间即可参与抢红包/)
        if (isShareRedPacket && isShareRedPacket.length > 0) {
            const [, count, total, btn] = isShareRedPacket;
            const moneyCount = parseInt(count.trim())
            if (moneyCount > maxCount) {
                maxCount = moneyCount;
            }
            return { count: moneyCount, total: parseInt(total.trim()), type: 4, btn: btn.trim(), text };
        }
        return { text, index };
    });
    if (maxCount <= 0) {
        throw new Error(`暂无红包`)
    }
    return { redPacketsList, maxCount };
}

function clickShareAndCopy() {
    const router = new Router()
    try {
        $.clickButton($.getVisibleElementById('live_bottom_bar_single_icon_container'))
        router.push('CLICK_SHARE_BUTTON')
        sleep(2000);
        $.clickButton(selector().visibleToUser(true).id("live_bottom_bar_item_title_text_view").text(`分享`).findOne(3000))
        sleep(2000);
        $.clickButton($.getVisibleElementByText(`复制链接`))
        router.pop()
        sleep(2000);
    } catch (e) {
        router.home();
    }
}
function getRoomLink() {
    clickShareAndCopy()
    sleep(2000)
    const link = getClip()
    if (link) {
        const res = link.match(/(http.*?)\s(.*?)的直播/)
        if (res && res.length > 0) {
            const link = res[1]
            const name = res[2]
            const _streamLink = getRealLink(link)
            return {
                name,
                originLink: link,
                ..._streamLink || {}
            }
        }
    }
}
function toNextLiveRoom() {
    sleep(1000 * 10)
    $.swipeUp()
    return getLiveRoomRedPacketInfo()
}
function roomGroupBy(node: UiObject | undefined): string | undefined {
    if (!node) return;
    const parent = node.parent();
    if (!parent) return;
    if (parent.className() === `androidx.viewpager.widget.ViewPager`) {
        if (node.className() === 'android.widget.FrameLayout') {
            const bounds = node.bounds()
            return `${bounds.left}_${bounds.right}`
        } else {
            log(`roomGroupBy:node class name is ${node.className()} depth is ${node.depth()}`)
        }
    }
    return roomGroupBy(parent)
}
function getRoomInfoNodeGroupBy() {
    const nodes = selector().textMatches(/.{1,30}/).find()
    const list: Map<string, Set<UiObject>> = new Map();
    nodes.map(node => {
        const parent = roomGroupBy(node)
        if (parent) {
            const item = list.get(parent) || new Set()
            item.add(node)
            list.set(parent, item)
        } else {
            log(`node parent is empty`)
        }
    })
    return list;
}
export function getRedPacketInfo() {
    const LIVE_RED_PACKET_TEXT_IDS: string[] = [
        'common_red_packet_pop_prepare_reward_desc_view',
        'live_condition_leee_button_text',
        'live_red_packet_fling_tips',
        'red_packet_cover_reward_usual_count',
        'red_packet_cover_reward_usual_unit',
        'prepare_reward_password_text_view',
        'second_line_text_view',
        'title_text_view',
        'progress_text_view',
        'red_packet_cover_reward_usual_count',
        'red_packet_cover_reward_usual_unit',
        'first_line_text_view',
        'first_line_text_view',
        'red_packet_pop_prepare_source_desc_view',
        'live_sec_kill_red_packet_pop_prepare_reward_kcoin_view',
        'live_sec_kill_prepare_reward_desc_text_view',
        'count_down_text_view',
        'tips_text_view',
        'red_packet_cover_reward_sub_pack_count',
        'icon_desc_text_view'
    ];
    const nodes = getRoomInfoNodeGroupBy();
    const rooms: any[] = [];
    nodes.forEach(list => {
        const room: any = {
            __text: ``
        }
        list.forEach(node => {
            const id = node.id();
            const text = node.text();
            room.__text += `${text} `;
            const item = LIVE_RED_PACKET_TEXT_IDS.find(it => id && id.endsWith(it))
            if (item) {
                const [pkg, name] = id.split('/')
                const val = { text: node.text(), node }
                room[name] = val
            } else {
                log(`getRedPacketInfo:${id}`)
            }
        })
        if (Object.keys(room).length > 1) {
            rooms.push(room)
        }
    })
    return rooms;
}
/**
 * 获取房间信息
 * @returns
 */
function getLiveRoomInfo() {

    const LIVE_ROOM_TEXT_IDS: string[] = [
        'text',
        'live_name_text',
        'live_audience_count_text',
        'live_hourly_rank_content_view',
        'live_side_bar_pendant_text_view',
        'live_red_packet_status_text',
        'live_red_packet_count',
        'live_top_right_common_pendant_count_down',
        'live_multi_chat_user_name',
        'live_multi_chat_gift_text',
        'title',
        'subtitle_number',
        'subtitle',
        'action_button',
        'live_activity_red_packet_count_text_view',
        'live_activity_red_packet_display_text_view',
        'live_interact_programme_title_text_view',
        'live_interact_programme_pendant_programme_item_text',
        'live_interact_programme_pendant_body_btn_text',
        'live_follow_text',
        'live_wish_list_name_text_view',
        'live_wish_list_destination_text_view',
        'live_gift_slot_username',
        'live_gift_slot_gift_des',
        'live_gift_slot_combo_count',
        'content_text_view',
        'live_multi_pk_user_tag',
        'live_multi_pk_user_name',
        'live_multi_pk_score_grade',
        'live_multi_pk_left_score_text_view',
        'live_multi_pk_right_score_text_view',
        'live_multi_pk_count_down_time',
        'live_player_bottom_quality_button'
    ]
    const nodes = getCurrentViewNodes(() => selector().textMatches(/.{0,30}/))
    const open_time = dayjs()
    const room: any = {
        __text: ``,
        open_time: open_time
    }
    nodes.map(node => {
        const id = node.id();
        const text = node.text();
        room.__text += `${text} `;
        const item = LIVE_ROOM_TEXT_IDS.find(it => id && id.endsWith(it))
        if (item) {
            const [pkg, name] = id.split('/')
            const val = { text: node.text(), node }
            room[name] = val
        }
    });
    return room;
}

function openSetting(packageName: string) {
    // 创建意图对象
    const intent = app.intent({
        action: "android.settings.APPLICATION_DETAILS_SETTINGS",
        data: "package:" + packageName
    });
    // 启动应用设置页面
    app.startActivity(intent);
}
/**
 * 关闭指定应用
 * 6s
 */
export function killApp(packageName: string) {
    openSetting(packageName)
    sleep(1500)
    $.clickButton(selector().textMatches(/.*(强行|停止|结束).{0,3}/).findOne(3000))
    sleep(1500)
    $.clickButton(selector().textMatches(/(确[定认]|(强行|停止|结束).{0,3})/).findOne(3000))
    sleep(1500)
    back()
}
declare const Intent: any;
export function openKsLive(signal: boolean = true) {
    let flag: any = signal ? Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK : Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
    const uri = `kwai://liveaggregatesquare`
    const intent = app.intent({
        action: "android.intent.action.VIEW",
        data: uri,
        flags: flag
    });
    context.startActivity(intent);
}
